package com.ycy.dubbo.entity;

import java.util.Collection;
import java.util.Map;
import java.util.regex.Pattern;

public class SearchUtil {

  private static final int[] FLAG_LOOKUP = new int[Character.MAX_VALUE];

  private static final int FLAG_GLOBAL = 256;

  static {
    FLAG_LOOKUP['g'] = FLAG_GLOBAL;
    FLAG_LOOKUP['i'] = Pattern.CASE_INSENSITIVE;
    FLAG_LOOKUP['m'] = Pattern.MULTILINE;
    FLAG_LOOKUP['s'] = Pattern.DOTALL;
    FLAG_LOOKUP['c'] = Pattern.CANON_EQ;
    FLAG_LOOKUP['x'] = Pattern.COMMENTS;
    FLAG_LOOKUP['d'] = Pattern.UNIX_LINES;
    FLAG_LOOKUP['t'] = Pattern.LITERAL;
    FLAG_LOOKUP['u'] = Pattern.UNICODE_CASE;
  }

  static int regexFlag(final char c) {

    int flag = FLAG_LOOKUP[c];

    if (flag == 0) {
      throw new IllegalArgumentException(String.format("Unrecognized flag [%c]", c));
    }

    return flag;
  }

  public static int regexFlags(final String s) {
    int flags = 0;

    if (s == null) {
      return flags;
    }

    for (final char f : s.toLowerCase().toCharArray()) {
      flags |= regexFlag(f);
    }

    return flags;
  }

  public static boolean isEmpty(Collection<?> collection) {
    return collection == null || collection.isEmpty();
  }

  public static boolean isEmpty(Map<?, ?> map) {
    return map == null || map.isEmpty();
  }

  public static boolean hasText(String str) {
    return str != null && !str.isEmpty() && containsText(str);
  }

  private static boolean containsText(CharSequence str) {
    int strLen = str.length();

    for (int i = 0; i < strLen; ++i) {
      if (!Character.isWhitespace(str.charAt(i))) {
        return true;
      }
    }

    return false;
  }

}
